package com.morn.fanfou.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

public class SerializableListUtil {

	public static <E> void write(List<E> list, Context context, String fileName) {
		File cacheFile = new File(context.getCacheDir(), fileName);
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(new FileOutputStream(cacheFile));
			int size = list.size();
			size = size > 20 ? 20 : size;
			out.writeInt(size);
			for (int i = 0; i < size; i++) {
				if (list.get(i) instanceof Serializable) {
					out.writeObject(list.get(i));
				} else {
					out.writeObject(null);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <E> List<E> read(Context context, String fileName) {
		File cacheFile = new File(context.getCacheDir(), fileName);
		ObjectInputStream in = null;
		List<E> list = new ArrayList<E>();
		try {
			in = new ObjectInputStream(new FileInputStream(cacheFile));
			int elementCount = in.readInt();
			for (int i = 0; i < elementCount; i++) {
				list.add((E) in.readObject());
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return list;
	}

}
